<?php

namespace common\models\cms;

use Yii;
use common\helpers\Url;
use common\helpers\DateHelper;
use common\helpers\ArrayHelper;
use common\helpers\FormatConverter;
use common\logics\ShareLogic;
use common\models\user\UserFavorite;

/**
 * This is the model class for table "{{%cms_article}}".
 *
 * @property int $id
 * @property int $channel_id 频道ID
 * @property string $title 标题
 * @property string $format 文章格式：default普通文章，gallery图集，video视频
 * @property string $thumb 封面图
 * @property string $keywords 关键词
 * @property string $description 导读简介
 * @property string $url 外链地址
 * @property int $duration 视频时长
 * @property int $picture_nums 组图数量
 * @property int $allow_comment 允许评论，0禁止，1开启
 * @property string $author 撰稿人
 * @property int $author_id 撰稿人ID
 * @property int $top_at 置顶结束时间
 * @property int $recommend_at 推荐时间
 * @property int $created_at
 * @property int $updated_at
 * @property int $deleted_at
 * @property int $status 状态
 */
class CmsArticle extends \common\db\ActiveRecord implements \common\base\ShareDataInterface {

    /**
     * 文章状态
     */
    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * 是否开启评论
     */
    const ALLOW_COMMENT_YES = 1;
    const ALLOW_COMMENT_NO = 0;

    /**
     * 文章格式
     */
    const FORMAT_DEFAULT = 'default';
    const FORMAT_GALLERY = 'gallery';
    const FORMAT_VIDEO = 'video';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%cms_article}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['channel_id', 'duration', 'picture_nums', 'allow_comment', 'author_id', 'recommend_at', 'top_at', 'created_at', 'updated_at', 'deleted_at', 'status'], 'integer'],
            [['title'], 'required'],
            [['format'], 'string'],
            [['title'], 'string', 'max' => 80],
            [['thumb', 'keywords', 'description', 'url'], 'string', 'max' => 255],
            [['author'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'channel_id' => '频道ID',
            'title' => '标题',
            'format' => '文章格式：default普通文章，gallery图集，video视频',
            'thumb' => '封面图',
            'keywords' => '关键词',
            'description' => '导读简介',
            'url' => '外链地址',
            'duration' => '视频时长',
            'picture_nums' => '组图数量',
            'allow_comment' => '允许评论，0禁止，1开启',
            'author' => '撰稿人',
            'author_id' => '撰稿人ID',
            'recommend_at' => '推荐时间',
            'top_at' => '置顶结束时间',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'deleted_at' => 'Deleted At',
            'status' => '状态',
        ];
    }

    /**
     * 文章隶属栏目
     */
    public function getCategory() {
        return $this->hasOne(CmsChannel::className(), ['id' => 'channel_id']);
    }

    /**
     * 关联文章视频
     */
    public function getVideo() {
        return $this->hasOne(CmsArticleVideo::className(), ['article_id' => 'id']);
    }

    /**
     * 关联文章图片
     */
    public function getAlbums() {
        return $this->hasMany(CmsArticleGallery::className(), ['article_id' => 'id'])->andWhere([
            'comment_id' => 0
        ]);
    }

    public function getThumbs() {
        return $this->hasMany(CmsArticleGallery::className(), ['article_id' => 'id'])->andWhere([
            'comment_id' => 0
        ])->limit(3);
    }

    /**
     * 关联文章详情
     */
    public function getContent() {
        return $this->hasOne(CmsArticleData::className(), ['article_id' => 'id']);
    }

    /**
     * 关联文章评论
     */
    public function getComments() {
        return $this->hasMany(CmsArticleComment::className(), ['article_id' => 'id']);
    }

    /**
     * 关联文章屏蔽
     */
    public function getHides() {
        return $this->hasMany(CmsArticleShield::className(), ['article_id' => 'id']);
    }

    /**
     * 关联文章数据统计
     */
    public function getStats() {
        return $this->hasOne(CmsArticleStats::className(), ['article_id' => 'id']);
    }

    /**
     * 文章频道名称
     */
    public function getCatename() {
        return $this->getCategory()->select('name')->column();
    }

    /**
     * 检测获取用户是否点赞过
     */
    public function getLiked() {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        return $this->hasOne(CmsArticleLike::className(), ['article_id' => 'id'])->andWhere([
            'comment_id' => 0,
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    public function getCollects() {
        return $this->hasMany(UserFavorite::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserFavorite::MODEL_ARTICLE,
        ]);
    }

    /**
     * 检测获取用户是否收藏过
     */
    public function getCollected() {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        return $this->hasOne(UserFavorite::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserFavorite::MODEL_ARTICLE,
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    /**
     * 获取文章图集
     */
    public function getPictures() {
        if ($this->cover) {
            return (array) $this->cover;
        }
        $albums = array_filter(ArrayHelper::getColumn($this->albums, 'source'));
        $nums = count($albums);
        if (!$nums) {
            return [];
        }
        if ($nums > 2) {
            return array_slice($albums, 0, 3);
        }
        return array_slice($albums, 0, 1);
    }

    /**
     * 文章栏目名称
     */
    public function getCover($format = false) {
        if ($this->thumb) {
            return Url::attach($this->thumb);
        }
        if ($this->format === self::FORMAT_VIDEO) {
            return ArrayHelper::getValue($this->video, ($format ? 'thumb' : 'url'), '');
        } elseif ($this->format === self::FORMAT_GALLERY) {
            return ArrayHelper::getValue($this->albums, [0, 'source'], '');
        }
        return '';
    }

    /**
     * 文章详情内容
     */
    public function getBody() {
        if (!$this->content) {
            return '';
        }
        $content = $this->content->body;
        return FormatConverter::appendRemoteDomain($content, 'http://img.lnts.cn');
//        $this->_content = HtmlPurifier::process($content);
    }

    /**
     * 文章发布时间格式化
     * @return string 格式化后的日期
     */
    public function getPublishTime() {
        return Yii::$app->formatter->asRelativeTime($this->created_at);
    }

    /**
     * 评论开启状态
     * @return boolean
     */
    public function getAllowComment() {
        return (boolean) $this->allow_comment;
    }

    /**
     * 视频时长分割
     * @return string HH:ii:ss
     */
    public function getSplitDuration() {
        return DateHelper::toDuration($this->duration);
    }

    /**
     * 打开文章地址，根据不同类型打开不同webview
     * @return string
     */
    public function getLink() {
        return [
            'type' => 'article',
            'format' => $this->format,
            'id' => $this->id,
        ];
    }

    /**
     * 打开文章地址，根据不同类型打开不同webview
     * @return string
     */
    public function getWeblink() {
        if ($this->format == 'default') {
            return Url::weblink('article/' . $this->format . '/{id}', [
                'id' => $this->id
            ]);
        }
        return Url::weblink('article.' . $this->format, [
            'id' => $this->id
        ]);
    }

    /**
     * 获取文章分享数据
     * @return array
     */
    public function getShareData() {
        $model = new ShareLogic();
        $model->setAttributes([
            'type' => ShareLogic::TYPE_ARTICLE,
            'title' => $this->title,
            'content' => $this->description,
            'thumb' => $this->getCover(true),
        ]);
        $model->setParams([
            'id' => $this->id,
            'format' => $this->format,
        ]);
        return $model->toArray();
    }

    /**
     * 通过分享ID查询文章
     * @return array
     */
    public static function findShareById($id) {
        $model = static::findOne($id);
        if (!$model) {
            return null;
        }
        return $model->shareData();
    }

    /**
     * 接口返回基础数据结构
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'format',
            'title',
            'pictures',
            'category',
            'duration',
            'picture_nums',
            'stats',
            'allow_comment' => 'allowComment',
            'publish_time' => 'created_at',
        ];
    }

}
